<?php
namespace App\Controller;

use App\Services\PdfService;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;

#[AutoController]
class PdfController extends AbstractController
{
    #[Inject]
    private PdfService $pdfService;

    //accept upload word file and transfer it to pdf and then return url of that pdf
    public function word2Pdf()
    {
        //TODO 文件上传
        $request = $this->request->all();
        if (!$this->request->hasFile('word')) {
            return $this->error('缺少word文件');
        }
        if (!$this->request->file('word')->isValid()) {
            return $this->error('无效文件');
        }
        $fileExt = $this->request->file('word')->getExtension();
        if (!in_array($fileExt, ['doc', 'docx'])) {
            return $this->error('只支持doc或docx文件');
        }

        $wordPath = BASE_PATH . '/public/uploads/pdf_' . uniqid(). '.' . $fileExt;
        $file = $this->request->file('word');
        $file->moveTo($wordPath);
        if (!$file->isMoved()) {
            return $this->error('保存临时文件失败');
        }
        // $resp = PdfService::wordToPdf($request['word']);

        // return $this->request->getServerParams();
        $resp = PdfService::word2PdfByLibreoffice($wordPath);
        if ($resp === false) {
            return $this->error('生成pdf失败');
        }
        
        $defaultHost = ApplicationContext::getContainer()->get(\Hyperf\HttpServer\Server::class)->getServerName(). '://localhost:' . $this->request->server('server_port');
        $host = \hyperf\config\config('api_url', $defaultHost);
        @unlink($wordPath);
        return $this->success(['url' => rtrim($host, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . str_replace('public/', '', $resp)]);
    }
}